import 'package:flutter/material.dart';
import 'package:ninetyfour/l10n/app_localizations.dart';
import '../../login/view/custom_text_field.dart';
import '../../login/view/mobile_text_field.dart';
import '../../login/view/ercode_text_field.dart';
import '../../components/toast_utils.dart';
import '../../manger/network_utils.dart';
import '../../models/user_info_model.dart';
import '../../manger/user_manger.dart';
import '../../components/click_word_captcha.dart';

class BingPage extends StatefulWidget {
  final String titleName;
  
  const BingPage({super.key, required this.titleName});

  @override
  State<BingPage> createState() => _BingPageState();
}

class _BingPageState extends State<BingPage> {
  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _ercodeController = TextEditingController();
  final GlobalKey<ErcodeTextFieldState> _ercodeKey = GlobalKey();

  String btnName = '';
  String key = '';
  var arcode = '1';
  var area = 'US';
  bool isEnabled = true;
  bool isNext= false;
  var captchaVerification = '';

  @override
  void initState() {
    super.initState();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    
    if (widget.titleName == AppLocalizations.of(context)!.emailVerification) {
      setState(() {
        btnName = AppLocalizations.of(context)!.bindNow;
      });
    } else if (widget.titleName == AppLocalizations.of(context)!.phoneBinding) {
     setState(() {
        btnName = AppLocalizations.of(context)!.bindNow;
      });    
    } else {
     setState(() {
        btnName = AppLocalizations.of(context)!.nextone;
        _usernameController.text = UserInfos.shared.userModel?.mobile?.mobile ?? '';
        isEnabled = false;
      });
    }
  }


  void _bindAccount() async{
    if (_usernameController.text.isEmpty) {
      ToastUtils.showCenterToast(context, widget.titleName == AppLocalizations.of(context)!.emailVerification ? AppLocalizations.of(context)!.pleaseEnter +  AppLocalizations.of(context)!.mailbox : AppLocalizations.of(context)!.pleaseEnter + AppLocalizations.of(context)!.phoneNumber);
      return;
    }

    if (_usernameController.text.isEmpty) {
      ToastUtils.showCenterToast(context, AppLocalizations.of(context)!.pleaseEnter +  AppLocalizations.of(context)!.verificationCode );
      return;
    }

    var params = {};
    if (widget.titleName == AppLocalizations.of(context)!.emailVerification) {
      params = {
        'email': _usernameController.text,
        'sendType': 2,
        'code': _ercodeController.text,
      };
    } else if (widget.titleName == AppLocalizations.of(context)!.phoneBinding) {
      params = {
        'areCode': arcode,
        'countryCode': area,
        'code': _ercodeController.text,
        'phone': _usernameController.text,
      };
    } else {
      params = {
        'code': _ercodeController.text,
      };
    }

    ToastUtils.showLoadingToast(context);

    try {
      final response = await NetworkUtils.post(
        widget.titleName == AppLocalizations.of(context)!.emailVerification 
            ? RequestCmd.authenticationEmail 
            : widget.titleName == AppLocalizations.of(context)!.phoneBinding 
                ? RequestCmd.authenticationPhone 
                : RequestCmd.changeBind,
        body: params,
      );
      ToastUtils.dismissLoadingToast();
      if (response['code'] == 200) {
        if (widget.titleName == AppLocalizations.of(context)!.changePhone){
          setState(() {
            _usernameController.text = '';
            _ercodeController.text = '';
            btnName = AppLocalizations.of(context)!.bindNow;
            isEnabled = true;
            isNext = true;
            key = response['data'];
          });

        } else {
          ToastUtils.showCenterToast(context, response['msg']?? '绑定成功');
          Navigator.of(context).popUntil((route) => route.isFirst);
        }
      }else {
        ToastUtils.showCenterToast(context, response['msg'] ?? '绑定失败,请联系客服');
      }
    } catch (e) {
      ToastUtils.dismissLoadingToast();
      print('Error fetching user info: $e');
    }
  }  

  void sendCode() async {
    if (_usernameController.text.isEmpty) {
      ToastUtils.showCenterToast(context, widget.titleName == AppLocalizations.of(context)!.emailVerification ? AppLocalizations.of(context)!.pleaseEnter +  AppLocalizations.of(context)!.mailbox : AppLocalizations.of(context)!.pleaseEnter + AppLocalizations.of(context)!.phoneNumber);
      return;
    }

    var params = {};
    if (widget.titleName == AppLocalizations.of(context)!.emailVerification) {
      params = {
        'email': _usernameController.text,
        'sendType': 2,
        'captchaVerification': captchaVerification,
      };
    } else if (widget.titleName == AppLocalizations.of(context)!.phoneBinding) {
      params = {
        'areaCode': arcode,
        'countryCode': area,
        'type': 3,
        'phone': _usernameController.text,
        'captchaVerification': captchaVerification,
      };
    } else {
      params = {
        'type': 1,
        'captchaVerification': captchaVerification,
      };
    }

    ToastUtils.showLoadingToast(context);

    try {
      final response = await NetworkUtils.post(
        widget.titleName == AppLocalizations.of(context)!.emailVerification 
            ? RequestCmd.sendEmailCode 
            : widget.titleName == AppLocalizations.of(context)!.phoneBinding 
                ? RequestCmd.sendPhoneCode 
                : RequestCmd.sendcodeC,
        body: params,
      );
      captchaVerification = "";
      ToastUtils.dismissLoadingToast();
      final model = PhoneCodeModel.fromJson(response);
      if (model.code == 200) {
        if (model.data?.boolValue != null) {
          // 处理bool情况
          final boolValue = model.data!.boolValue!;
          if(boolValue){
            loadingClickWord(context,0);
          }
        } else {
          ToastUtils.showCenterToast(context, model.msg ?? '发送成功');
          _ercodeKey.currentState?.startCountdown();
        }
      }else {
        ToastUtils.showCenterToast(context, model.msg ?? '发送失败,请联系客服');
      }
    } catch (e) {
      ToastUtils.dismissLoadingToast();
      print('Error fetching user info: $e');
    }

  }

  sendNextCode() async {
    var params = {
      'areaCode': arcode,
      'countryCode': area,
      'type': 1,
      'phone': _usernameController.text,
      'captchaVerification': captchaVerification,
    };

    ToastUtils.showLoadingToast(context);
    try {
      final response = await NetworkUtils.post(
        RequestCmd.sendPhoneCode,
        body: params,
      );
      captchaVerification = "";
      ToastUtils.dismissLoadingToast();
      final model = PhoneCodeModel.fromJson(response);
      if (model.code == 200) {

        if (model.data?.model != null) {
          ToastUtils.showCenterToast(context, model.msg ?? '发送成功');
          _ercodeKey.currentState?.startCountdown();
        } else if (model.data?.boolValue != null) {
          // 处理bool情况
          final boolValue = model.data!.boolValue!;
          if(boolValue){
            loadingClickWord(context,1);
          }
        }
      }else {
        ToastUtils.showCenterToast(context, model.msg ?? '发送失败,请联系客服');
      }
    } catch (e) {
      ToastUtils.dismissLoadingToast();
      print('Error fetching user info: $e');
    }
  }

  void loadingClickWord(BuildContext context,int type, {barrierDismissible = true}) {
    showDialog<Null>(
      context: context,
      barrierDismissible: barrierDismissible,
      builder: (BuildContext context) {
        return ClickWordCaptcha(
          onSuccess: (v){
            captchaVerification = v;
            if (type == 0) {
              sendCode();
            } else {
              sendNextCode();
            }
          },
          onFail: (){
          },
        );
      },
    );
  }

    void _bindAccount2() async{
    if (_usernameController.text.isEmpty) {
      ToastUtils.showCenterToast(context, widget.titleName == AppLocalizations.of(context)!.emailVerification ? AppLocalizations.of(context)!.pleaseEnter +  AppLocalizations.of(context)!.mailbox : AppLocalizations.of(context)!.pleaseEnter + AppLocalizations.of(context)!.phoneNumber);
      return;
    }

    if (_usernameController.text.isEmpty) {
      ToastUtils.showCenterToast(context, AppLocalizations.of(context)!.pleaseEnter +  AppLocalizations.of(context)!.verificationCode );
      return;
    }

    var params = {
        'areaCode': arcode,
        'countryCode': area,
        'type': 1,
        'key': key,
        'code': _ercodeController.text,
        'phone': _usernameController.text,
      };

    ToastUtils.showLoadingToast(context);
    print('params Info: $params');

    try {
      final response = await NetworkUtils.post(
        widget.titleName == AppLocalizations.of(context)!.emailVerification 
            ? RequestCmd.authenticationEmail 
            : widget.titleName == AppLocalizations.of(context)!.phoneBinding 
                ? RequestCmd.authenticationPhone 
                : RequestCmd.changeBind,
        body: params,
      );
      ToastUtils.dismissLoadingToast();
      if (response['code'] == 200) {
        if (widget.titleName == AppLocalizations.of(context)!.changePhone){
          setState(() {
            _usernameController.text = '';
            _ercodeController.text = '';
            btnName = AppLocalizations.of(context)!.bindNow;
            isEnabled = true;
            isNext = true;
          });

        } else {
          ToastUtils.showCenterToast(context, response['msg']?? '绑定成功');
          Navigator.of(context).popUntil((route) => route.isFirst);
        }
      }else {
        ToastUtils.showCenterToast(context, response['msg'] ?? '绑定失败,请联系客服');
      }
    } catch (e) {
      ToastUtils.dismissLoadingToast();
      print('Error fetching user info: $e');
    }
  }  

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        toolbarHeight: 40,
        title: Text(widget.titleName, style: const TextStyle(fontSize: 17)),
      ),
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 35),
        child: Column(
          children: [
            const SizedBox(height: 35),
            widget.titleName == AppLocalizations.of(context)!.emailVerification
                ? CustomTextField(
                  controller: _usernameController,
                  hintText: '${AppLocalizations.of(context)!.pleaseEnter}${AppLocalizations.of(context)!.mailbox}',
                  )
                : MobileTextField(
                  controller: _usernameController,
                  hintText: '${AppLocalizations.of(context)!.pleaseEnter}${AppLocalizations.of(context)!.phoneNumber}',
                  enabled: isEnabled,
                  onCodeValueChanged: (value) {
                    setState(() {
                      final parts = value.split(' ');
                      area = parts[0];
                      arcode = parts[1].startsWith('+') ? parts[1].substring(1) : parts[1];
                    });
                  },
                ),
            const SizedBox(height: 25),
            ErcodeTextField(controller: _ercodeController,
            key: _ercodeKey,
            onSendCode: (value) {       
              if (isNext) {
                sendNextCode();
              } else {
                sendCode();
              }            
            },),
            const SizedBox(height: 30),
            SizedBox(
              height: 48,
              width: double.infinity,
              child: ElevatedButton(
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFF5D5FEE),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(24),
                  ),
                ),
                onPressed: isNext? _bindAccount2 : _bindAccount,
                child: Text(btnName, style: const TextStyle(fontSize: 16, color: Colors.white)),
              ),
            ),
            Expanded(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  Align(
                    alignment: Alignment.centerLeft,
                    child: Padding(
                      padding: const EdgeInsets.only(right: 35),
                      child: Text(
                        AppLocalizations.of(context)!.didNotReceiveTheVerificationCode,
                        style: const TextStyle(color: Color(0xFF3b8cfe),fontSize: 16),
                      ),
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(bottom: 50, top: 15),
                    child: Text(
                      widget.titleName == AppLocalizations.of(context)!.emailVerification 
                          ? AppLocalizations.of(context)!.emailVerificationTips  
                          : AppLocalizations.of(context)!.phoneVerificationTips,
                      style: const TextStyle(color: Color(0xFF666666)),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
      
    );
  }
}
